<template>
  <base-content>
    <template>
      <el-form ref="form" :model="form" label-width="180px">
        <el-form-item label="商品名称" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-input v-model="form.product_name" required placeholder="请输入商品名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="商品价格" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-input v-model="form.price" type="number" placeholder="请输入标价，保留两位小数" />
          </el-col>
        </el-form-item>
        <el-form-item label="优惠后价格" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-input v-model="form.price_discount" type="number" placeholder="请输入实际售价，2位小数" />
          </el-col>
        </el-form-item>
        <el-form-item label="商品类型" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.product_type" placeholder="请选择商品类型">
              <el-option label="商品" :value="1" />
              <el-option label="服务" :value="2" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="商品规格" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-input v-model="form.product_attribute" :type="form.product_type === 1 ? 'text' : 'number'" placeholder="请输入商品规格" />
          </el-col>
        </el-form-item>
        <el-form-item label="可使用机构" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.can_use_dept_id_list" multiple placeholder="请选择可使用机构">
              <el-option v-for="item in jigouList" :key="item.id" :label="item.dept_name" :value="item.id" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="商品提供方" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.provider_dept_id" :disabled="form.id !== ''" placeholder="请选择商品类型">
              <el-option v-for="(dept, pIndex) in upDepList" :key="pIndex" :label="dept.dept_name" :value="dept.id" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="库存" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-input v-model="form.quantity" type="number" placeholder="请输入库存数量" />
          </el-col>
        </el-form-item>
        <el-form-item label="可售卖范围">
          <el-col :span="14">
            <rm-tree-select
              ref="wl-tree-select"
              v-model="form.sale_scope_list"
              check-on-click-node
              node-key="id"
              width="240"
              checkbox
              no-checked-close
              :data="treeData"
              :default-expand-all="false"
              :default-expanded-keys="[1]"
              @change="scopeSelectChange"
            />
            <p>不选任意值，全平台可售卖，首页推荐范围内</p>
          </el-col>
        </el-form-item>
        <el-form-item label="平台分成（积分）" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.product_rate_list[0].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.product_rate_list[0].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="运营中心分成（积分）" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.product_rate_list[1].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.product_rate_list[1].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="咨询中心分成（积分）" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.product_rate_list[2].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.product_rate_list[2].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="使用机构（积分）" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.product_rate_list[3].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.product_rate_list[3].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="推荐者分成（积分）" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.product_rate_list[4].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.product_rate_list[4].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="商品轮播图" :rules="[{ required: true }]">
          <el-col :span="16">
            <el-upload
              name="file"
              action="/api/api/admin/img/upload?type=1"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :file-list="fileList"
              :headers="headers"
              :on-error="handleError"
              accept="image/png, image/jpeg, image/jpg, image/webp"
              :on-success="handleSuccess"
              list-type="picture-card"
              :limit="5"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png/webp文件，最多只能上传5张，宽高比例为4：3
              </div>
            </el-upload>
          </el-col>
        </el-form-item>
        <el-form-item label="商品详情图" :rules="[{ required: true }]">
          <el-col :span="20">
            <el-upload
              name="file"
              action="/api/api/admin/img/upload?type=1"
              :on-preview="handlePreview"
              :on-remove="handleDetailRemove"
              :file-list="fileList2"
              :before-upload="beforeDetailUpload"
              :headers="headers"
              :on-error="handleError"
              accept="image/png, image/jpeg, image/jpg, image/webp"
              :on-success="handleDetailSuccess"
              list-type="picture-card"
              :limit="10"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png/wepb文件，最多只能上传10张
              </div>
            </el-upload>
          </el-col>
        </el-form-item>
        <el-form-item label="商品状态" :rules="[{ required: true }]">
          <el-col :span="4">
            <el-select v-model="form.status" placeholder="请选择活动区域">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </template>
  </base-content>
</template>

<script>
import { mapGetters } from 'vuex'
import { createPlatformProduct, getDeptList, getPlatformProductDetail, updatePlatformProduct } from '@/api/production-api'
import { apiUrl } from '@/utils/config'
import RmTreeSelect from '@/components/sl-tree.vue'

export default {
  components: { RmTreeSelect },
  data() {
    const token = localStorage.getItem('token')
    return {
      headers: {
        token
      },
      treeData: [
        {
          id: '0',
          name: '所有平台',
          children: []
        }
      ],
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      fileList2: [],
      upDepList: [],
      selected: ['4'],
      deptType: '',
      form: {
        id: '',
        product_name: '',
        price: '',
        price_discount: '',
        product_type: '',
        product_attribute: '',
        provider_dept_id: '',
        sale_scope_list: [],
        can_use_dept_id_list: [],
        product_rate_list: [
          { rate_type: '', rate_value: '', role_type: 1 },
          { rate_type: '', rate_value: '', role_type: 2 },
          { rate_type: '', rate_value: '', role_type: 3 },
          { rate_type: '', rate_value: '', role_type: 4 },
          { rate_type: '', rate_value: '', role_type: 5 }
        ],
        product_desc_url: '',
        status: '',
        product_img_list: [],
        quantity: ''
      },
      selsAreas: [],
      jigouList: []
    }
  },
  async created() {
    const result = await getDeptList()
    if (result.code === '0') {
      const list = result.info.data
      this.selsAreas = result.info.data
      this.jigouList = list.filter((item) => item.dept_type === 4)
      // 初始化第一层数据
      const treeList = list.filter((item) => item.dept_parent_id === 0)
      const trees = []
      this.upDepList = list.filter((dep) => dep.dept_type === 4)
      treeList.forEach((item) => {
        const arr = this.toTreeData(list, item.id)
        trees.push({ id: item.id, name: item.dept_name, children: arr })
      })
      this.treeData[0].children = trees
      // const treeDatas = this.treeData
      // this.treeData = trees
    } else {
      this.selsAreas = []
    }
  },
  async mounted() {
    const query = this.$route.query
    if (query && query.id) {
      const result = await getPlatformProductDetail({ id: query.id })
      if (result.code === '0') {
        const entity = result.info.data
        if (!entity.product_rate_list || !entity.product_rate_list.length) {
          entity.product_rate_list = [
            { rate_type: '', rate_value: '', role_type: 1 },
            { rate_type: '', rate_value: '', role_type: 2 },
            { rate_type: '', rate_value: '', role_type: 3 },
            { rate_type: '', rate_value: '', role_type: 4 },
            { rate_type: '', rate_value: '', role_type: 5 }
          ]
        }
        if (!entity.product_img_list || !entity.product_img_list) {
          entity.product_img_list = []
        }
        this.form = result.info.data
        this.deptType = result.info.data.product_type
        const files = result.info.data.product_img_list || []
        const fileList = files.filter((file) => file.img_flag === 1).map((item) => {
          return { url: `${apiUrl}${item.img_url}`, name: 'file', img_url: item.img_url, img_flag: item.img_flag }
        })
        const fileList2 = files.filter((file) => file.img_flag === 2).map((item) => {
          return { url: `${apiUrl}${item.img_url}`, name: 'file', img_url: item.img_url, img_flag: item.img_flag }
        })
        this.$nextTick(() => {
          const scopeList = result.info.data.sale_scope_list || []
          this.sale_scope_list = scopeList && scopeList.map((item) => item.toString())
        })
        this.fileList = fileList || []
        this.fileList2 = fileList2 || []
      }
    }
  },
  methods: {
    toTreeData(data, pid) {
      function tree(id) {
        const arr = []
        data.filter(item => {
          return item.dept_parent_id === id
        }).forEach(item => {
          arr.push({
            id: item.id,
            name: item.dept_name,
            children: tree(item.id)
          })
        })
        return arr
      }
      // 第一级节点的父id，是null或者0，视情况传入
      return tree(pid)
    },
    filterDeps(list, id) {
      return list.filter((item) => id === item.dept_parent_id)
    },
    labelText(item) {
      return `${item.id}-${item.dept_name}`
    },
    scopeSelectChange(val) {
      const scopeIds = val.map((item) => item.id).filter((item) => Number(item) !== 0)
      this.form.sale_scope_list = scopeIds
    },
    async onSubmit() {
      const params = this.form
      const fileList = this.fileList
      const fileList2 = this.fileList2
      const numberValue = /^[0-9]+$/
      const floatValue = /^(\d+)(.\d{0,2})?$/
      // 校验商品
      if (!params.product_name) {
        return this.$message.error('商品名称不能为空')
      }
      if (!params.price) {
        return this.$message.error('请输入商品价格')
      }
      if (!floatValue.test(params.price)) {
        return this.$message.error('商品价格保留两位小数')
      }
      if (!params.price_discount) {
        return this.$message.error('请输入优惠后商品价格')
      }
      if (!floatValue.test(params.price_discount)) {
        return this.$message.error('商品价格保留两位小数')
      }
      if (!params.product_type) {
        return this.$message.error('请选择商品类型')
      }
      if (!params.product_attribute) {
        return this.$message.error('请输入商品规格')
      }
      if (!params.can_use_dept_id_list.length) {
        return this.$message.error('请选择可使用机构')
      }
      if (!params.provider_dept_id) {
        return this.$message.error('请选择商品提供方')
      }
      if (!params.quantity) {
        return this.$message.error('请输入商品库存')
      }
      // 校验库存
      if (!/^[0-9]+$/.test(params.quantity)) {
        return this.$message.error('库存只能是正整数类型')
      }
      if (params.product_rate_list[0].rate_type === '') {
        return this.$message.error('请选择平台分成类型')
      }
      if (params.product_rate_list[0].rate_type === 1 && !numberValue.test(params.product_rate_list[0].rate_value)) {
        return this.$message.error('平台分成只输入正整数')
      }
      if (params.product_rate_list[0].rate_type === 2 && !floatValue.test(params.product_rate_list[0].rate_value)) {
        return this.$message.error('平台分成数字格式错误，最多保留两位小数')
      }
      if (params.product_rate_list[1].rate_type === '') {
        return this.$message.error('请选择运营中心类型')
      }
      if (params.product_rate_list[1].rate_type === 1 && !numberValue.test(params.product_rate_list[1].rate_value)) {
        return this.$message.error('运营中心分成只输入正整数')
      }
      if (params.product_rate_list[1].rate_type === 2 && !floatValue.test(params.product_rate_list[1].rate_value)) {
        return this.$message.error('运营中心分成数字格式错误，最多保留两位小数')
      }
      if (params.product_rate_list[2].rate_type === '') {
        return this.$message.error('请选择咨询中心分成类型')
      }
      if (params.product_rate_list[2].rate_type === 1 && !numberValue.test(params.product_rate_list[2].rate_value)) {
        return this.$message.error('咨询中心分成只输入正整数')
      }
      if (params.product_rate_list[2].rate_type === 2 && !floatValue.test(params.product_rate_list[2].rate_value)) {
        return this.$message.error('咨询中心分成数字格式错误，最多保留两位小数')
      }
      if (params.product_rate_list[3].rate_type === '') {
        return this.$message.error('请选择使用机构分成类型')
      }
      if (params.product_rate_list[3].rate_type === 1 && !numberValue.test(params.product_rate_list[3].rate_value)) {
        return this.$message.error('使用机构分成只输入正整数')
      }
      if (params.product_rate_list[3].rate_type === 2 && !floatValue.test(params.product_rate_list[3].rate_value)) {
        return this.$message.error('使用机构分成数字格式错误，最多保留两位小数')
      }
      if (params.product_rate_list[4].rate_type === '') {
        return this.$message.error('请选择推荐者分成类型')
      }
      if (params.product_rate_list[4].rate_type === 1 && !numberValue.test(params.product_rate_list[4].rate_value)) {
        return this.$message.error('推荐者分成只输入正整数')
      }
      if (params.product_rate_list[4].rate_type === 2 && !floatValue.test(params.product_rate_list[4].rate_value)) {
        return this.$message.error('推荐者分成数字格式错误，最多保留两位小数')
      }
      if (!fileList.length) {
        return this.$message.error('请上传轮播图片')
      }
      if (!fileList2.length) {
        return this.$message.error('请上传商品详情图')
      }
      if (params.status === '') {
        return this.$message.error('请选择商品状态')
      }
      const images = []
      fileList.forEach((item, index) => {
        images.push({ img_position: (index + 1), img_url: item.img_url, img_flag: item.img_flag })
      })
      fileList2.forEach((item, index) => {
        images.push({ img_position: (index + 1), img_url: item.img_url, img_flag: item.img_flag })
      })
      this.form.product_img_list = images
      const scopeList = this.form.sale_scope_list || []
      if (scopeList && scopeList.length > 0) {
        const sale_scopes = scopeList.length && scopeList.map((item) => item.toString())
        const sale_scope_list = Array.from(new Set(sale_scopes))
        this.form.sale_scope_list = sale_scope_list
      }
      const query = this.$route.query
      if (query && query.id) {
        const result = await updatePlatformProduct(JSON.stringify(params))
        if (result.code === '0') {
          this.$message.success('编辑成功')
          this.$router.push('/plantproduct/list')
        } else {
          this.$message.error('编辑失败：' + result.msg)
        }
      } else {
        const result = await createPlatformProduct(JSON.stringify(params))
        if (result.code === '0') {
          this.$message.success('创建成功')
          this.$router.push('/plantproduct/list')
        } else {
          this.$message.error('创建失败：' + result.msg)
        }
      }
    },
    cancel() {
      this.$router.push('/product/list')
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleDetailRemove(file, fileList) {
      this.fileList2 = fileList
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleError(err, file, fileList) {
      this.$message.error(`上传失败：${err.msg}`)
    },
    filterFiles(file) {
      this.fileList = this.fileList && this.fileList.filter((f) => file.uid !== f.uid)
      this.fileList2 = this.fileList2 && this.fileList2.filter((f) => file.uid !== f.uid)
    },
    beforeDetailUpload(file) {
      const product_img_list = this.fileList2 || []
      const imageList = product_img_list.filter((item) => item.img_flag === 2)
      if (imageList.length >= 10) {
        this.$message.error('最多只能上传10张图')
        return false
      }
    },
    beforeUpload(file) {
      const product_img_list = this.fileList || []
      const imageList = product_img_list.filter((item) => item.img_flag === 1)
      if (imageList.length >= 5) {
        this.$message.error('最多只能上传5张图')
        return false
      }
    },
    // 商品轮播图
    handleSuccess(result, file, fileList) {
      if (result.code === '0001') {
        this.$message.error(`上传失败：${result.msg}`)
        this.filterFiles(file)
      } else if (result.code === '9999') {
        window.location.href = '/#/login'
      } else {
        this.$message.success('上传成功')
        fileList.forEach((item) => {
          if (file.uid === item.uid) {
            item.img_url = result.info.data
            item.img_flag = 1
          }
        })
        this.fileList = fileList
      }
    },
    // 商品详情图
    handleDetailSuccess(result, file, fileList) {
      if (result.code === '0001') {
        this.$message.error(`上传失败：${result.msg}`)
        this.filterFiles(file)
      } else if (result.code === '9999') {
        window.location.href = '/#/login'
      } else {
        this.$message.success('上传成功')
        fileList.forEach((item) => {
          if (file.uid === item.uid) {
            item.img_url = result.info.data
            item.img_flag = 2
          }
        })
        this.fileList2 = fileList
      }
    }
  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapGetters(['sidebar']),
    routes() {
      return this.$router.options.routes
    }
  }
}
</script>

<style scoped>
.el-select {
  width: 100%
}
</style>
